package model

import (
	"time"
	"user_srv/basic/config"

	"gorm.io/gorm"
)

type UserInventory struct { //用户背包表
	Id         uint      `gorm:"column:id;type:bigint;comment:主键ID;primaryKey;not null;" json:"id"`                           // 主键ID
	UserId     uint      `gorm:"column:user_id;type:bigint;comment:用户ID;not null;" json:"user_id"`                            // 用户ID
	GoodsId    uint      `gorm:"column:goods_id;type:int;comment:商品ID;not null;" json:"goods_id"`                             // 商品ID
	Quantity   int       `gorm:"column:quantity;type:int;comment:商品数量;not null;" json:"quantity"`                             // 商品数量
	Status     uint      `gorm:"column:status;type:tinyint;comment:状态：1-未使用 2-已使用 3-已过期;not null;" json:"status"`             // 状态：1-未使用 2-已使用 3-已过期
	ExpireTime time.Time `gorm:"column:expire_time;type:datetime;comment:过期时间（NULL表示永久）;default:NULL;" json:"expire_time"`    // 过期时间（NULL表示永久）
	CreateTime time.Time `gorm:"column:create_time;type:datetime;comment:获得时间;default:CURRENT_TIMESTAMP;" json:"create_time"` // 获得时间
	UpdateTime time.Time `gorm:"column:update_time;type:datetime;comment:更新时间;default:CURRENT_TIMESTAMP;" json:"update_time"` // 更新时间
}

// 背包详情关联结构体
type UserInventoryDetail struct {
	Id           uint      `json:"id"`
	UserId       uint      `json:"user_id"`
	GoodsId      uint      `json:"goods_id"`
	Quantity     int       `json:"quantity"`
	Status       uint      `json:"status"`
	ExpireTime   time.Time `json:"expire_time"`
	CreateTime   time.Time `json:"create_time"`
	GoodsName    string    `json:"goods_name"`
	ImageUrl     string    `json:"image_url"`
	GoodsType    uint      `json:"goods_type"`
	EffectConfig string    `json:"effect_config"`
	Description  string    `json:"description"`
}

func (ui *UserInventory) TableName() string {
	return "user_inventory"
}
func (ui *UserInventory) CreateInventory() error { //创建用户背包
	return config.DB.Create(&ui).Error
}
func (ui *UserInventory) GetUserInventory(where *UserInventory) error { //获取用户背包中的商品
	return config.DB.Where(where).Limit(config.Limit).Find(&ui).Error
}
func (ui *UserInventory) UpdateInventory(where *UserInventory) error { //更新背包记录
	return config.DB.Model(&UserInventory{}).Where(where).Updates(&ui).Error
}

// 构建背包查询基础Query
func (ui *UserInventory) BuildInventoryQuery(userId uint, goodsType int) *gorm.DB {
	query := config.DB.Table("user_inventory ui").
		Select("ui.*, vg.name as goods_name, vg.image_url, vg.type as goods_type, vg.effect_config, vg.description").
		Joins("LEFT JOIN virtual_goods vg ON ui.goods_id = vg.id").
		Where("ui.user_id = ? AND ui.status = 1", userId)

	if goodsType > 0 {
		query = query.Where("vg.type = ?", goodsType)
	}

	return query.Order("ui.create_time DESC")
}

// 获取用户背包列表
func (ui *UserInventory) GetUserInventoryList(userId uint, page, pageSize, goodsType int) ([]UserInventoryDetail, error) {
	var details []UserInventoryDetail

	query := ui.BuildInventoryQuery(userId, goodsType)
	err := query.Scopes(Paginate(page, pageSize)).Find(&details).Error

	return details, err
}

// 获取用户背包商品总数
func (ui *UserInventory) GetUserInventoryCount(userId uint, goodsType int) (int64, error) {
	var count int64

	query := ui.BuildInventoryQuery(userId, goodsType)
	err := query.Count(&count).Error

	return count, err
}
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB { //分页
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}
		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
